package io.renren.utils.aop;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.renren.entity.SysLogEntity;
import io.renren.service.SysLogService;

@Component 
public class SysLogConsumer implements Runnable{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	private static volatile boolean active = true;
	
	private static final int DEFAULT_BATCH_SIZE = 64;//默认一个批次处理64条  
	
	private int batchSize = DEFAULT_BATCH_SIZE;//批次处理条数，可以修改set
	
	@Autowired
	private SysLogService sysLogService;
    
	private Thread thread;
	
	@PostConstruct
	public void init(){
		thread = new Thread(this);
		thread.start();
	}
	
	@PreDestroy
	public void close(){
		active = false;
	}
	
	@Override
	public void run() {
		while(active){
			excute();
		}
	}
	
	public void excute(){
		List<SysLogEntity> sysLogs = new ArrayList<>();
		try{
			int size = 0;
			while(size < batchSize){
				SysLogEntity sysLog = SysLogQueue.poll();
				if(sysLog == null){
					break;
				}
				sysLogs.add(sysLog);
				size ++;
			}
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		
		if(!sysLogs.isEmpty()){
			sysLogService.saveBatch(sysLogs);
		}
	}

	public void setBatchSize(int batchSize) {
		this.batchSize = batchSize;
	}
	
}
